<?php
namespace Forxx;


class CallMonitor
{
	const SUCCESS = 1;
	const FAILED = 0;
	
	private static $monitor_items = array();
	private static $called_items = array();
	
	public static function begin_call($module, $interface)
	{
		self::$monitor_items[$module . '.' . $interface] = microtime(true);
	}
	
	public static function end_call($module, $interface, $result = self::SUCCESS, $response_code = 0)
	{
		if (!isset(self::$monitor_items[$module . '.' . $interface])) {
			return ;
		}
		
		self::$called_items[] = array(
			'module' => $module,
			'interface' => $interface,
			'begin_time' => self::$monitor_items[$module . '.' . $interface],
			'end_time' => microtime(true),
			'call_time' => round(microtime(true) - self::$monitor_items[$module . '.' . $interface], 5),
			'result' => $result,
			'code' => $response_code,
		);
		
		if (count(self::$called_items) > 20) {
			self::flush();
		}
	}
	
	public static function flush()
	{
		if (empty(self::$called_items)) {
			return ;
		}

		$old_mask = umask(0);

		//check & make dir
		$dir = L_WORKSPACE_PATH . 'log/' . L_APP_NAME . '/';
		if (!is_dir($dir)) {
			mkdir($dir, 0777, true);
		}

		//write file
		$file = $dir . date('Ymd');
		$contents = '';
		foreach (self::$called_items as $item) {
			$date = date('Y-m-d H:i:s', $item['begin_time']);
			$contents .= "{$date}\t" . implode("\t", $item) . "\n";
		}
		file_put_contents($file . '.monitor', $contents, FILE_APPEND | LOCK_EX);

		//keep small than 1G
		if (filesize($file . '.monitor') > 1000000000) {
			rename($file . '.monitor', $file . '.' . date('His') . '.log');
		}

		umask($old_mask);

		//clear
		self::$called_items = array();
	}
}

register_shutdown_function(array('\\Forxx\\CallMonitor', 'flush') );
